<template>
  <div>
    <el-form ref="form" :rules="rules" size="mini" inline :model="form" label-width="80px">
      <el-row>
        <el-col :span="24">
          <el-form-item label="视图类型" prop="reportType">
            <el-select v-model="form.reportType">
              <el-option v-for="item in reportTypeList" :value="item.value" :label="item.label" :key="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="表"prop="table">
            <el-select  @change="changeTable" v-model="form.table">
              <el-option v-for="item in tableList" :value="item.value" :label="item.label" :key="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="选择列" prop="columns">
            <el-select v-model="form.columns" multiple clearable style="width: 200px;">
              <el-option v-for="item in tableInfo.selectColumnList" :value="item.value" :label="item.label" :key="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
        <el-row>
          <el-col>
            <el-form-item label="求和">
              <el-select v-model="form.sumFields" multiple clearable>
                <el-option v-for="item in tableInfo.aggregationColumnList" :value="item.value" :label="item.label" :key="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="最大值">
              <el-select v-model="form.maxFields" multiple clearable>
                <el-option v-for="item in tableInfo.aggregationColumnList" :value="item.value" :label="item.label" :key="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="最小值">
              <el-select v-model="form.minFields" multiple clearable>
                <el-option v-for="item in tableInfo.aggregationColumnList" :value="item.value" :label="item.label" :key="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="平均值">
              <el-select v-model="form.avgFields" multiple clearable>
                <el-option v-for="item in tableInfo.aggregationColumnList" :value="item.value" :label="item.label" :key="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="计数">
              <el-select v-model="form.countFields" multiple clearable>
                <el-option v-for="item in tableInfo.countColumnList" :value="item.value" :label="item.label" :key="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="起始日期" prop="from">
              <el-date-picker type="date" placeholder="起始日期" v-model="form.from" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
            </el-form-item>
            <el-form-item label="结束日期" prop="to">
              <el-date-picker type="date" placeholder="结束日期" v-model="form.to" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询</el-button>
        <el-button>取消</el-button>
      </el-form-item>
    </el-form>
    <el-table border show-summary  :summary-method="getSummaries" :data="dataObjectList" highlight-current-row style="width: 100%">
      <el-table-column v-for="(col,index) in tableColumns"
                       :key="index"
                       :prop="col.value"
                       :label="col.label" :formatter="formatNumber">
      </el-table-column>
    </el-table>
    <div id="main" style="height: 340px;"></div>
  </div>
</template>

<script>
  import {list, tableList} from '@/api/crm/report'
  import * as echarts from "echarts";
  export default {
    name: "reportIndex",
    data() {
      return {
        //解析后的数据，数据项为map
        dataList: [],
        //解析后的数据，数据项为Object，给表格用的
        dataObjectList: [],
        tableColumns: [],
        columnMap: new Map(),
        form: {
          from: '2020-01-01 00:00:00',
          to: '2022-10-01 23:59:59',
          reportType: 'MONTH',
          table: 'tb_contract',
          columns: [],
          sumFields: [],
          maxFields: [],
          minFields: [],
          avgFields: [],
          countFields: [],
          dateField: 'create_time',
        },
        rules: {
          reportType:[{ required: true, message: "报表类型不能为空", trigger: "blur" }],
          table:[{ required: true, message: "数据表不能为空", trigger: "blur" }],
          columns:[{ required: true, message: "列不能为空", trigger: "blur" }],
          from:[{ required: true, message: "起始日期不能为空", trigger: "blur" }],
          to:[{ required: true, message: "结束日期不能为空", trigger: "blur" }],
        },
        tableInfo: [],
        reportTypeList:[
          {'label':'日', 'value':'DATE'},
          {'label':'周', 'value':'WEEK'},
          {'label':'月', 'value':'MONTH'},
          {'label':'季', 'value':'QUARTER'},
          {'label':'年', 'value':'YEAR'},
        ],
        tableList:[
          {'label':'合同表', 'value':'tb_contract'},
          {'label':'商机表', 'value':'tb_business'},
        ],
      }
    },
    created() {
      // this.refreshData()
      this.tableInfo = tableList['tb_contract']
    },
    methods: {
      onSubmit() {
        this.$refs.form.validate(valid=>{
          if(valid) {
            if(this.isEmpty(this.form.maxFields) && this.isEmpty(this.form.minFields)
              && this.isEmpty(this.form.avgFields) && this.isEmpty(this.form.sumFields)
              && this.isEmpty(this.form.countFields)) {
              this.$alert('至少选择一个统计操作')
              return false
            }
            // 设置列label
            let labels = [];
            // labels.push(this.getLabels(this.reportTypeList, this.form.reportType));
            labels.push(this.getLabels(this.tableInfo.selectColumnList, this.form.columns));
            labels.push(this.getLabels(this.tableInfo.aggregationColumnList, this.form.sumFields, 'sum_',':和'));
            labels.push(this.getLabels(this.tableInfo.aggregationColumnList, this.form.maxFields, 'max_',':最大'));
            labels.push(this.getLabels(this.tableInfo.aggregationColumnList, this.form.minFields, 'min_',':最小'));
            labels.push(this.getLabels(this.tableInfo.aggregationColumnList, this.form.avgFields, 'avg_',':平均'));
            labels.push(this.getLabels(this.tableInfo.countColumnList, this.form.countFields, 'count_',':计数'));
            // 删除empty array
            labels = labels.filter(item => item.length > 0);

            this.columnMap = new Map();
            labels.forEach(item => {
              item.forEach(labelObj => {
                this.columnMap.set(labelObj.value, labelObj.label)
              })
            })
            this.columnMap.set('date', this.reportTypeList.find(item => item.value == this.form.reportType).label);
            console.log(this.columnMap);
            this.refreshData();
          }
        })
      },
      refreshData() {
        console.log(this.form);
        list(this.form).then(resp => {
            // this.renderEcharts(resp.data)
            this.dataList = resp.data
            this.tableColumns = [];
            this.dataObjectList = [];

            //处理数据，以符合el-table
            this.dataList.forEach(item => {
              // //map转Object
              // let obj = Object.create(null);
              // for(let[k,v] of item) {
              //   obj[k] = v;
              // }
              // this.dataObjectList.push(obj);
              if(item.date && item.year && this.form.reportType != 'DATE') {
                item.date = item.year + '年' + item.date + this.reportTypeList.find(item=>item.value == this.form.reportType).label
              }
              if(this.form.reportType != 'YEAR') {
                delete item.year
              }
              this.dataObjectList.push(item);
            })
            //初始化列
            for(let item of Object.keys(this.dataList[0])) {
              let label = this.columnMap.get(item);
              this.tableColumns.push({label: label ? label : item, value: item})
            }
          })
      },
      changeTable(val) {
        this.form.columns.length = 0;
        this.form.sumFields.length = 0;
        this.form.maxFields.length = 0;
        this.form.minFields.length = 0;
        this.form.avgFields.length = 0;
        this.form.countFields.length = 0;
        this.tableInfo = tableList[val]
      },
      isEmpty(obj) {
        return !obj || obj.length == 0;
      },
      getLabels(datas, values, prefix = '', suffix = '') {
        var actions = [];
        if (values === undefined) {
          return actions;
        }
        if(!Array.isArray(values)) {
          values = [values];
        }
        for(let value of values) {
          Object.keys(datas).some((key) => {
            if (datas[key].value == ('' + value)) {
              actions.push({label: datas[key].label + suffix, value: prefix + value});
              return true;
            }
          })
        }
        return actions;

      },

      getSummaries(param) {
        const { columns, data } = param;
        const sums = [];
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '合计';
            return;
          }
          let reg = /^max_|^min_|^avg_|^sum_|^count_/;
          if( !reg.test(column.property) ) {
            return;
          }
          const values = data.map(item => Number(item[column.property]));
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            sums[index] += '';
          } else {
            sums[index] = 'N/A';
          }
        });
        for(let i = 0; i < sums.length; i++) {
          if(!isNaN(sums[i])) {
            sums[i] = parseFloat('' + sums[i]).toFixed(2);
          }
        }
        return sums;
      },
      formatNumber(row, column, cellValue, index) {
        let reg = /^max_|^min_|^avg_|^sum_/;
        if(reg.test(column.property) ) {
          if(cellValue) {
            return parseFloat('' + cellValue).toFixed(2);
          } else {
            return '0.00';
          }
        } else {
          return cellValue;
        }
      },

      /*renderEcharts(obj) {
        let dateArr = [];
        let orderArr = [];
        let performedArr = [];
        obj.forEach(item => {
          dateArr.push(this.formatCategory(item, this.form.type));
          orderArr.push(item.orderQty);
          performedArr.push(item.performedQty);
        });
        var chartDom = document.getElementById('main');
        var myChart = echarts.init(chartDom);
        var option;

        option = {
          title: {
            text: this.formatTitle(this.form.type),
            subtext: ''
          },
          tooltip: {
            trigger: 'axis',
            show: false
          },
          legend: {
            data: ['派工数', '完成数']
          },
          toolbox: {
            show: true,
            feature: {
              dataView: { show: true, readOnly: false },
              magicType: { show: true, type: ['line', 'bar'] },
              restore: { show: true },
              saveAsImage: { show: true }
            }
          },
          calculable: true,
          //X轴上柱子的数据
          xAxis: [
            {
              type: 'category',
              // prettier-ignore
              data: []
            }
          ],
          yAxis: [
            {
              type: 'value'
            }
          ],
          series: [
            {
              name: '派工数',
              type: 'bar',
              barWidth : 20, //柱图宽度
              data: [

              ],
              //在柱子顶端展示数据的最大值最小值气泡
              // markPoint: {
              //     data: [
              //         { type: 'max', name: 'Max' },
              //         { type: 'min', name: 'Min' }
              //     ]
              // },
              //展示数据平均值线
              markLine: {
                data: [{ type: 'average', name: 'Avg' }]
              },
              // 用于在每根柱子上展示数据
              label: {
                show: true,
                position: 'top',
                color:'black'
              }
            },
            {
              name: '完成数',
              type: 'bar',
              barWidth : 20, //柱图宽度
              data: [

              ],
              //在柱子顶端展示数据的最大值最小值气泡
              // markPoint: {
              //     data: [
              //         { type: 'max', name: 'Max' },
              //         { type: 'min', name: 'Min' }
              //     ]
              // },
              markLine: {
                data: [{ type: 'average', name: 'Avg' }]
              },
              label: {
                show: true,
                position: 'top',
                color:'black'
              }
            },
          ]
        };

        //注意，必须用这种语法来传递数据
        option.xAxis[0].data = dateArr;
        option.series[0].data = orderArr;
        option.series[1].data = performedArr;
        console.log(orderArr);
        console.log(performedArr);
        option && myChart.setOption(option);
      }*/
    }
  }
</script>

<style scoped>
  .el-select,.el-input {
    width: 140px;
  }
</style>
